package com.xyulu.controller.blog;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyulu.entity.BlogCommentsEntity;
import com.xyulu.entity.common.Result;
import com.xyulu.service.BlogCommentsService;
import com.xyulu.utils.ShiroUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author Xyulu
 * @Date 2021/4/11 14:20
 * @Version 1.0
 */
@Controller
public class CommentController {

    @Resource
    private BlogCommentsService commentsService;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId") Integer blogId,
                           HttpServletRequest request){
        //获取所有顶级评论
        List<BlogCommentsEntity> list = commentsService.listComments(blogId);
        //为顶级评论填充回复
        List<BlogCommentsEntity> comments = commentsService.handleComments(list);

        request.setAttribute("comments",comments);
        request.setAttribute("user",ShiroUtil.getLocalUserName());
        return "blog/article_details::commentList";
    }

    @PostMapping("/comments/postComment")
    @ResponseBody
    public Result postComment(@RequestBody BlogCommentsEntity comment){
        //构造数据
        comment.setCreateTime(new Date());
        comment.setCreateBy(ShiroUtil.getLocalUserId());
        try {
            commentsService.save(comment);
        } catch (Exception e) {
            return new Result(400,"评论新增失败");
        }
        return new Result(200,"评论新增成功");
    }

    @PostMapping("/comments/removeComment")
    @ResponseBody
    public Result removeComment(@RequestBody BlogCommentsEntity comment){
        try {
            commentsService.remove(Wrappers.<BlogCommentsEntity>lambdaQuery()
                    .eq(BlogCommentsEntity::getId, comment.getId())
                    .or().eq(BlogCommentsEntity::getReplyTo, comment.getId()));
        } catch (Exception e) {
            return new Result(400,"评论删除失败");
        }
        return new Result(200,"评论删除成功");
    }

}
